<template>
  <div class="exam">
    <el-table :data="examInfo.arr" border v-loading="loading">
      <el-table-column fixed="left" prop="subject" label="试卷名称" width="180"></el-table-column>
      <el-table-column prop="description" label="描述" width="200"></el-table-column>
      <el-table-column prop="practiceOrExam" label="考试/练习" width="200"></el-table-column>
      <el-table-column prop="paperId" label="所属题库" :formatter="formatterPaper" width="200"></el-table-column>
      <el-table-column prop="institute" label="所属学院" width="120"></el-table-column>
      <el-table-column prop="major" label="所属专业" width="200"></el-table-column>
      <el-table-column prop="grade" label="考试年级" width="100"></el-table-column>
      <el-table-column prop="clazz" label="考试班级" width="100"></el-table-column>
      <el-table-column prop="examDate" label="考试日期" width="120"></el-table-column>
      <el-table-column prop="time" label="考试时长" width="120"></el-table-column>
      <el-table-column prop="examScore" label="试卷总分" width="120"></el-table-column>
      <el-table-column prop="type" label="试卷类型" width="120"></el-table-column>
      <el-table-column prop="tips" label="考生提示" width="400"></el-table-column>
      <el-table-column fixed="right" label="操作" width="150">
        <template #default="scope">
          <el-button @click="editExam(scope.$index,scope.row)" type="primary" size="small">编辑</el-button>
          <el-button @click="deleteExam(scope.row.id)" type="danger" size="small">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-config-provider :locale="zhCn">
      <el-pagination
          @size-change="pageSizeChange"
          @current-change="pageNumChange"
          :current-page="pagination.pageNum"
          :page-sizes="[3, 6, 9, 12]"
          :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total">
      </el-pagination>
    </el-config-provider>
    <!-- 编辑对话框-->
    <el-dialog
        title="编辑试卷信息"
        v-model="dialogVisible"
        width="30%"
        :before-close="handleClose">
      <section class="update">
        <el-form ref="changExamRef" :model="examInfo.edit" label-width="80px">
          <el-form-item label="考试课程"
                        prop="subject"
                        :rules="[{required: true, message: '考试课程不能为空', trigger: 'change'}]">
            <el-input v-model="examInfo.edit.subject"></el-input>
          </el-form-item>
          <el-form-item label="考试描述"
                        prop="description"
                        :rules="[{required: true, message: '考试描述不能为空', trigger: 'change'}]">
            <el-input v-model="examInfo.edit.description"></el-input>
          </el-form-item>
          <el-form-item label="考试/练习"
                        prop="practiceOrExam"
                        :rules="[
                            {required: true, message: '考试/练习不能为空', trigger: 'change'},
                            {validator: checkPracticeOrExam, trigger: 'change'}
                            ]">
            <el-input v-model="examInfo.edit.practiceOrExam"></el-input>
          </el-form-item>
          <el-form-item label="所属题库"
                        prop="paperId"
                        :rules="[
                            {required: true, message: '请选择题库', trigger: 'change'},
                            ]">
            <el-select v-model="examInfo.edit.paperId" class="m-2" placeholder="Select">
              <el-option
                  v-for="(item,index) in examInfo.paper"
                  :key="index"
                  :label="item.id +': '+item.paperName"
                  :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="所属学院"
                        prop="institute"
                        v-if="role === '0'"
                        :rules="[{required: true, message: '所属学院不能为空', trigger: 'change'}]">
            <el-input v-model="examInfo.edit.institute"></el-input>
          </el-form-item>
          <el-form-item label="所属学院"
                        v-if="role === '1'">
            <el-input v-model="examInfo.edit.institute" disabled></el-input>
          </el-form-item>
          <el-form-item label="所属专业"
                        prop="major"
                        :rules="[{required: true, message: '所属专业不能为空', trigger: 'change'}]">
            <el-input v-model="examInfo.edit.major"></el-input>
          </el-form-item>
          <el-form-item label="考试年级"
                        prop="grade"
                        :rules="[
                              {required: true, message: '年级不能为空', trigger: 'change'},
                              {validator: checkNumber, trigger: 'change'}
                            ]">
            <el-input v-model="examInfo.edit.grade"></el-input>
          </el-form-item>
          <el-form-item label="考试班级"
                        prop="clazz"
                        :rules="[
                              {required: true, message: '班级不能为空', trigger: 'change'},
                              {validator: checkNumber, trigger: 'change'}
                            ]">
            <el-input v-model="examInfo.edit.clazz"></el-input>
          </el-form-item>
          <el-form-item label="考试日期"
                        prop="examDate"
                        :rules="[{required: true, message: '请选择考试日期', trigger: 'change'}]">
            <el-col :span="11">
              <el-date-picker type="date" placeholder="选择日期" v-model="examInfo.edit.examDate" style="width: 100%;"></el-date-picker>
            </el-col>
          </el-form-item>
          <el-form-item label="考试时长"
                        prop="time"
                        :rules="[
                              {required: true, message: '考试时长不能为空', trigger: 'change'},
                              {validator: checkNumber, trigger: 'change'}
                            ]">
            <el-input v-model="examInfo.edit.time"></el-input>
          </el-form-item>
          <el-form-item label="考试总分"
                        prop="examScore"
                        :rules="[
                              {required: true, message: '考试时长不能为空', trigger: 'change'},
                              {validator: checkNumber, trigger: 'change'}
                            ]">
            <el-input v-model="examInfo.edit.examScore"></el-input>
          </el-form-item>
          <el-form-item label="试卷类型"
                        prop="type"
                        :rules="[{required: true, message: '试卷类型不能为空', trigger: 'change'}]">
            <el-input v-model="examInfo.edit.type"></el-input>
          </el-form-item>
          <el-form-item label="考生提示">
            <el-input type="textarea" v-model="examInfo.edit.tips"></el-input>
          </el-form-item>
        </el-form>
      </section>
      <template v-slot:footer>
        <el-button @click="editBack()">取 消</el-button>
        <el-button type="primary" @click="editSubmit()">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {getCurrentInstance, onMounted, reactive, ref} from "vue";
import AES from '@/utils/AESUtil'
import {ElMessage, ElMessageBox} from "element-plus";
import {isObjectValueEqual} from "@/utils/funUtils";
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
export default {
  name: "selectExam",
  setup(){
    const {proxy} = getCurrentInstance()
    let changExamRef = ref(null)
    let loading = ref(false) //加载标识符
    let dialogVisible = ref(false)
    // eslint-disable-next-line no-undef
    let role = ref(AES.Decrypt($cookies.get("role")))
    let examInfo = reactive({
      arr: [],
      edit: {},
      editIndex: null,
      paper: []
    })
    let pagination = reactive({
      pageNum: 1, //当前页
      total: Number(''), //记录条数
      pageSize: 3 //每页条数
    })
    let checkPracticeOrExam = (rule,value,callback) => {
      if (value === '考试' || value === '练习') {
        callback()
      }else {
        callback(new Error('只能输入考试/练习'))
      }
    }
    let checkNumber = (rule,value,callback) => {
      const boolean = new RegExp('^[1-9][0-9]*$').test(value)
      if (!boolean) {
        callback(new Error('请输入正整数'))
      }else {
        callback()
      }
    }
    let formatterPaper = (row, column,cellValue) => {
      //row每行的内容 column每一列的属性信息 cellValue单元格的值
      if(cellValue){ //不包含值为 0 的情况 另做判断
        let paper = examInfo.paper.filter((item)=>{
          return item.id === cellValue
        })
        return cellValue + ': ' + paper[0].paperName
      }else{
        return '--' //没有值时展示 --
      }
    }
    onMounted(()=>{
      getExamInfo()
    })
    function getExamInfo(){
      // eslint-disable-next-line no-undef
      loading.value = true
      proxy.$axios.get(
          `/manage/paper`
      ).then(
          response => {
            examInfo.paper = response.data
          },
          error => {
            console.log('请求失败', error.message)
          }
      )
      if (role.value === '1'){
        proxy.$axios.get(
            // eslint-disable-next-line no-undef
            `/manage/exams/${$cookies.get("id")}/${pagination.pageNum}/${pagination.pageSize}`
        ).then(
            response => {
              examInfo.arr = [...response.data.list]
              pagination.total = response.data.total
              pagination.pageNum = response.data.pageNum
              pagination.pageSize = response.data.pageSize
              loading.value = false
            },
            error => {
              console.log('请求失败', error.message)
            }
        )
      }else if (role.value === '0'){
        proxy.$axios.get(
            // eslint-disable-next-line no-undef
            `/manage/exams/${pagination.pageNum}/${pagination.pageSize}`
        ).then(
            response => {
              examInfo.arr = [...response.data.list]
              pagination.total = response.data.total
              pagination.pageNum = response.data.pageNum
              pagination.pageSize = response.data.pageSize
              loading.value = false
            },
            error => {
              console.log('请求失败', error.message)
            }
        )
      }
    }
    function pageSizeChange(value){//改变当前记录条数
      pagination.pageSize = value
      getExamInfo()
    }
    function pageNumChange(value){//改变当前页码
      pagination.pageNum = value
      getExamInfo()
    }
    function editExam(index,value){
      dialogVisible.value = true
      examInfo.editIndex = index
      examInfo.edit = {...value}
    }

    function editSubmit(){
      proxy.$refs.changExamRef.validate((valid) => {
        if (valid) {
          if (isObjectValueEqual(examInfo.arr[examInfo.editIndex],examInfo.edit)){
            ElMessage({
              type: 'info',
              message: '信息没有改动',
            })
            return false
          }
          proxy.$axios.put(
              // eslint-disable-next-line no-undef
              `/manage/exam/update`,
              {...examInfo.edit}
          ).then(
              response => {
                if (response.data) {
                  ElMessage({
                    type: 'success',
                    message: '修改成功',
                  })
                  dialogVisible.value = false
                  getExamInfo()
                }
              },
              error => {
                console.log('请求失败', error.message)
              }
          )
        }else {
          return false
        }
      })
    }
    function editBack(){
      dialogVisible.value = false
      ElMessage({
        type: 'info',
        message: '取消修改',
      })
      proxy.$refs.changExamRef.clearValidate()
    }
    function handleClose(done){
      ElMessageBox.confirm('确认关闭？',"",
          {
            confirmButtonText: '是',
            cancelButtonText: '否',
            type: 'warning',
          }
      ).then(() => {
        done();
        ElMessage({
          type: 'info',
          message: '取消修改',
        })
      }).catch(() => {});
    }
    function deleteExam(id) {
      ElMessageBox.confirm(
          '是否永久删除该考试信息,该操作不可逆！！！',
          '警告',
          {
            confirmButtonText: '是',
            cancelButtonText: '否',
            type: 'warning',
          }
      ).then(() => {
        proxy.$axios.delete(`/manage/exam/delete/${id}`).then(
            response => {
              if (response.data){
                ElMessage({
                  type: 'success',
                  message: '删除成功',
                })
                getExamInfo()
              }
            },
            error => {
              console.log('请求失败', error.message)
            }
        )
      }).catch(() => {
        ElMessage({
          type: 'info',
          message: '取消删除',
        })
      })
    }
    return{
      role,
      loading,
      changExamRef,
      pagination,
      examInfo,
      dialogVisible,
      pageSizeChange,
      pageNumChange,
      editExam,
      checkNumber,
      checkPracticeOrExam,
      editBack,
      handleClose,
      editSubmit,
      deleteExam,
      formatterPaper,
      zhCn
    }
  }
}
</script>

<style scoped>
.exam {
  padding: 0px 40px;
}
.exam .page {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
}
.exam .edit{
  margin-left: 20px;
}
</style>